package l2ft.gameserver.model.entity.events.impl.fightclub;

import l2ft.commons.collections.MultiValueSet;
import l2ft.gameserver.ThreadPoolManager;
import l2ft.gameserver.model.Creature;
import l2ft.gameserver.model.Player;
import l2ft.gameserver.model.Skill;
import l2ft.gameserver.model.entity.events.fightclubmanager.FightClubPlayer;
import l2ft.gameserver.model.entity.events.fightclubmanager.FightClubTeam;
import l2ft.gameserver.model.entity.events.impl.AbstractFightClub;

public class LastTeamStandingEvent extends AbstractFightClub
{
	public LastTeamStandingEvent(MultiValueSet<String> set)
	{
		super(set);
	}
	
	@Override
	public void onKilled(Creature actor, Creature victim, Skill skill)
	{
		if(actor != null && actor.isPlayable())
		{
			FightClubPlayer fActor = getFightClubPlayer(actor.getPlayer());
			if(victim.isPlayer())
			{
				fActor.increaseKills(true);
				updatePlayerScore(fActor);
				sendMessageToPlayer(fActor, MESSAGE_TYPES.HERO, "You have killed "+victim.getName());
			}
			else if(victim.isPet())
			{
				
			}
			actor.getPlayer().sendUserInfo();
		}
		
		if(victim.isPlayer())
		{
			FightClubPlayer fVictim = getFightClubPlayer(victim);
			fVictim.increaseDeaths();
			if(actor != null)
				sendMessageToPlayer(fVictim, MESSAGE_TYPES.HERO, "You have been killed by "+actor.getName());
			victim.getPlayer().sendUserInfo();
			
			checkRoundOver();
		}
		
		super.onKilled(actor, victim, skill);
	}
	
	@Override
	public void startRound()
	{
		super.startRound();
		checkRoundOver();
	}
	
	private void checkRoundOver()
	{
		if(getState() != EVENT_STATE.STARTED)
			return;
		
		int aliveTeams = 0;
		FightClubTeam aliveTeam = null;
		System.out.println("checking round over, teams:"+getTeams().size());
		for(FightClubTeam team : getTeams())
		{
			System.out.println("players in team:"+team.getPlayers().size());
			for(FightClubPlayer iFPlayer : team.getPlayers())
				if(!iFPlayer.getPlayer().isDead())
				{
					System.out.println("not dead player:"+iFPlayer.getPlayer().getName());
					aliveTeams++;
					aliveTeam = team;
				}
		}
		
		if(aliveTeams == 1)
		{
			System.out.println("Alive team:"+aliveTeam.getName()+" color:"+aliveTeam.getNickColor());
			aliveTeam.incScore(1);
			updateScreenScores();
			announceWinnerTeam(false, aliveTeam);
			setState(EVENT_STATE.OVER);
			
			ThreadPoolManager.getInstance().schedule(new Runnable() {
				
				@Override
				public void run()
				{
					endRound();
				}
			}, 5*1000);
		}
	}
	
	@Override
	public String getVisibleTitle(Player player, String currentTitle, boolean toMe)
	{
		FightClubPlayer realPlayer = getFightClubPlayer(player);
		
		if(realPlayer == null)
			return currentTitle;
		
		return "Kills: " + realPlayer.getKills(true) + " Deaths: "+realPlayer.getDeaths();
	}
}
